import { CSSProperties, PropType, defineComponent, ref } from "vue"
import classes from "./index.module.scss"

export type TelescopingLeftType = {
  width?: string,
  height?:string,
  minWidth?: string,
  maxWidth?: string,
  minHeight?: string,
  maxHeight?:string
}

function test() {
  const test = ref("50%")
    const testRef = ref<HTMLDivElement | null>(null) 
    const isDrag = ref(false)
    const onMousemove = (e: MouseEvent) => {
      console.log(e);
      
      isDrag.value && (test.value = `${e.clientX + e.offsetX}px`) && console.log(e.clientX , testRef.value.clientWidth);
    }

    const changeDrag = () => { 
      isDrag.value = !isDrag.value
    }

    const onMousedown = () => {
      isDrag.value = !isDrag.value
      
      console.log(testRef.value.clientWidth, testRef.value.offsetWidth);
    }
}

function useTelescopDrag(firstConfig: TelescopingLeftType | undefined, type: "row" | "column") {
  const changeType = type === "row" ? 'width' : "height"
  const firstRef = ref<HTMLDivElement | null>(null)
  
  const firstLength = ref(firstConfig?.[changeType]  || 'calc(50% - 5px)')

  const onDrag = (e: DragEvent) => {
    const { offsetX,clientY } = e 
    if (type === "row") { 
      firstLength.value = `${firstRef.value.clientWidth + offsetX}px`
    } else {
      firstLength.value = `${clientY - 105}px`
    }
  }

  // 重置拖拽样式
  const onDragstart = (e: DragEvent) => {
    const img = new Image()
    e.dataTransfer.setDragImage(img, 0, 0)
  }

  // 渲染第一个节点的Style
  const getFirstNodeStyle = () => firstConfig ? { ...firstConfig, [changeType]: firstLength.value } : { [changeType]: firstLength.value }
  
  return { onDrag, onDragstart, firstRef, getFirstNodeStyle }
}

export default defineComponent({
  props: {
    firstConfig: {
      type: Object as PropType<TelescopingLeftType>
    },
    type: {
      type: String as PropType<"row" | "column">,
      default: "row"
    },
  },
  setup(props, ctx) {
    
    const { firstRef, onDrag, onDragstart, getFirstNodeStyle } = useTelescopDrag(props.firstConfig, props.type)

    return () => {
      const FirstNode = ctx.slots.firstNode()
      const SecondNode = ctx.slots.secondNode()
      return (
        <div class={`m-fullBox ${classes.telescoping} ${classes[props.type]}`}>
          <div
            ref={firstRef}
            class={classes[`firstNode-${props.type}`]}
            style={getFirstNodeStyle() as CSSProperties}>
            {FirstNode}
          </div>
          <div class={`allCenter ${classes.tool} `}>
            <div
              class={`cursorPointer allCenter ${classes.drag} ${classes[`drag-${props.type}`]}`}
              draggable
              onDragstart={onDragstart}
              onDrag={onDrag}
              onClick={(e)=> e.stopPropagation()}
            >
              |||
            </div>
          </div>
          <div class={classes.right} style={{ flex: 1 }}>{SecondNode}</div>
        </div>
      )
    }
  },
})